Solution Review: Problem Challenge 2

Path with Maximum Sum (hard) #

Find the path with the maximum sum in a given binary tree. Write a function that returns the maximum sum. A path can be defined as a sequence of nodes between any two nodes and doesn’t necessarily pass through the root.

Created with Fabric.js 1.6.0-rc.1 Example 1: 1 2 3 4 5 6 Output: 16Explanation: The path with maximum sum is: [4, 2, 1, 3, 6]
Created with Fabric.js 1.6.0-rc.1 Example 2: 1 2 3 1 3 5 6 7 8 9 Output: 31Explanation: The path with maximum sum is: [8, 5, 3, 6, 9]

Solution #

This problem follows the Binary Tree Path Sum pattern and shares the algorithmic logic with Tree Diameter. We can follow the same DFS approach. The only difference will be to ignore the paths with negative sums. Since we need to find the overall maximum sum, we should ignore any path which has an overall negative sum.

Code #

Here is what our algorithm will look like, the most important changes are in the highlighted lines:

Output

0.484s

Maximum Path Sum: 6 Maximum Path Sum: 31 Maximum Path Sum: -1

Time complexity #

The time complexity of the above algorithm is O(N)O(N), where ā€˜N’ is the total number of nodes in the tree. This is due to the fact that we traverse each node once.

Space complexity #

The space complexity of the above algorithm will be O(N)O(N) in the worst case. This space will be used to store the recursion stack. The worst case will happen when the given tree is a linked list (i.e., every node has only one child).

Mark as Completed
←    Back
Problem Challenge 2
Next    →
Introduction